import React from 'react';
import {Card, Button,Table,message,Form,Select,Input,Modal,Tree} from 'antd';
import Utils from '../../utils/utils'
import axios from '../../axios'
import menuConfig from '../../config/menuConfig'
const FormItem = Form.Item;
const Option = Select.Option;
const TreeNode = Tree.TreeNode;
export default class Permission extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            loading: true,
            dataSource: [],
            visible:false,
            isPermissionVisible:false
        }
    }

    params = {
        page: 1
    };

    componentDidMount() {
        this.request();
    }

    request = () => {
        let that = this;
        axios.Axios({
            url: "permission/list",
            method: 'get',
            params: this.params.page
        }).then(res => {
            this.setState({
                dataSource: res.list,
                loading: false,
                pagination: Utils.pagination(res, (current) => {
                    that.params.page = current;
                    this.request()
                })
            })
        })
    };

    onRowClick = (record, index) => {
        let selectKey = [index+1];
        this.setState({
            selectedRowKeys: selectKey,
            selectedItem: record
        })
    };
    // 创建角色
    handleRole = () => {
        this.setState({
            visible:true
        })
    };
    // Modal ok提交
    handleRoleSubmit = () => {
        let data = this.roleForm.props.form.getFieldsValue();
        axios.Axios({
            url:'city/open',
            method:'post',
            data
        }).then(res => {
            message.success(res.message);
            this.setState({
                visible:false
            });
            this.roleForm.props.form.resetFields();
            this.request()
        });
    };
    // 设置角色
    handlePermission() {
        let item = this.state.selectedItem;
        if(!item){
            message.info('请先选择一个角色');
            return false;
        }
        this.setState({
            isPermissionVisible:true,
            detailInfo:item,
            menuInfo:item.menus
        })
    }
    // 设置权限Modal ok
    handlePermEditSubmit = () => {
        let data = this.permForm.props.form.getFieldsValue();
        console.log(data);
        data.role_id = this.state.selectedItem.id;
        data.menus = this.state.menuInfo;
        axios.Axios({
            url:'city/open',
            method:'post',
            data
        }).then(res => {
            message.success(res.message);
            this.setState({
                isPermissionVisible:false
            });
            this.permForm.props.form.resetFields();
            this.request()
        });
    };


    render() {
        const columns = [
            {
                title:'角色ID',
                dataIndex:'Id'
            },
            {
                title:'角色名称',
                dataIndex:'role_name'
            },
            {
                title:'使用状态',
                dataIndex:'status',
                render: t => t===1 ? '启用' : '停用'
            },
            {
                title:'授权时间',
                dataIndex:'authorize_time'
            },
            {
                title:'授权人',
                dataIndex:'authorize_user_name'
            }
        ];

        const {selectedRowKeys} = this.state;
        const rowSelection = {
            type: 'radio',
            selectedRowKeys
        };

        return (
            <div className="wrap">
                <Card>
                    <Button type="primary" onClick={this.handleRole}>创建角色</Button>
                    <Button type="primary" onClick={this.handlePermission.bind(this)}>设置权限</Button>
                    <Button type="primary">用户授权</Button>
                </Card>
                <div className="content-wrap">
                    <Table
                        dataSource={this.state.dataSource}
                        pagination={this.state.pagination}
                        rowKey={record => record.id}
                        loading={this.state.loading}
                        columns={columns}
                        rowSelection={rowSelection}
                        onRow={(record,index) => {
                            return {
                                onClick: () => {
                                    this.onRowClick(record,index);
                                }
                            }
                        }}
                    />
                </div>
                <Modal
                    title="创建角色"
                    visible={this.state.visible}
                    onOk={this.handleRoleSubmit}
                    onCancel={() => {
                        this.roleForm.props.form.resetFields();  // 表单重置
                        this.setState({
                            visible:false
                        })
                    }}
                >
                    <RoleForm wrappedComponentRef={(inst) => this.roleForm=inst}/>
                </Modal>
                <Modal
                    title="设置权限"
                    visible={this.state.isPermissionVisible}
                    width={600}
                    onOk={this.handlePermEditSubmit}
                    onCancel={() => {
                        this.permForm.props.form.resetFields();  // 表单重置
                        this.setState({
                            isPermissionVisible:false
                        })
                    }}
                >
                    <PermEditForm
                        wrappedComponentRef={(inst) => this.permForm=inst}
                        detailInfo={this.state.detailInfo}
                        menuInfo={this.state.menuInfo}
                        patchMenuInfo={(checkedKeys) => {
                            this.setState({
                                menuInfo:checkedKeys
                            })
                        }}
                    />
                </Modal>
            </div>
        )
    }
}

// 角色创建
class RoleForm extends React.Component{

    render(){
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 16}
        };
        return (
            <Form layout="horizontal">
                <FormItem label="角色名称" {...formItemLayout}>
                    {
                        getFieldDecorator('role_name',{
                            initialValue:''
                        })(
                            <Input type="text" placeholder="请输入角色名称"/>
                        )
                    }
                </FormItem>
                <FormItem label="状态" {...formItemLayout}>
                    {
                        getFieldDecorator('state',{
                            initialValue:1
                        })(
                            <Select>
                                <Option value={1}>开启</Option>
                                <Option value={0}>关闭</Option>
                            </Select>
                        )}
                </FormItem>
            </Form>
        );
    }
}
RoleForm = Form.create({})(RoleForm);

class PermEditForm extends React.Component{

    onCheck = (checkedKeys) => {
        this.props.patchMenuInfo(checkedKeys)
    };

    //菜单递归
    renderTreeNodes = (data) => {
        return data.map((item) => {
            if(item.children) {
                return <TreeNode title={item.title} key={Math.random()*100}>
                    {this.renderTreeNodes(item.children)}
                </TreeNode>
            }else{
                return <TreeNode title={item.title} key={item.key}/>
            }
        })
    };
    render() {
        const { getFieldDecorator } = this.props.form;
        const {menuInfo} = this.props;
        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 16}
        };
        return (
            <Form layout="horizontal">
                <FormItem label='角色名称' {...formItemLayout}>
                    <Input disabled placeholder={this.props.detailInfo.role_name}/>
                </FormItem>
                <FormItem label='状态' {...formItemLayout}>
                    <Select>
                        {
                            getFieldDecorator('status',{
                                initialValue:1
                            })(
                                <Select>
                                    <Option value={1}>开启</Option>
                                    <Option value={0}>关闭</Option>
                                </Select>
                            )}
                    </Select>
                </FormItem>
                <Tree
                    checkable
                    defaultExpandAll
                    onCheck={(checkedKeys) => {
                        this.onCheck(checkedKeys)
                    }}
                    checkedKeys={menuInfo}
                >
                    <TreeNode title="平台权限" key="platform_all">
                        {this.renderTreeNodes(menuConfig)}
                    </TreeNode>
                </Tree>
            </Form>
        )
    }
}
PermEditForm = Form.create()(PermEditForm);